﻿namespace EFS.Common.Config
{
	/// <summary>
	/// Configuration reader
	/// </summary>
	public class Reader
	{ 
		/// <summary>
		/// Cached settings
		/// </summary>
		System.Collections.Generic.Dictionary<System.String, EFS.Common.Config.Components.Elements.Element> elements =
			new System.Collections.Generic.Dictionary<System.String, EFS.Common.Config.Components.Elements.Element>();

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="sectionPath"></param>
		public Reader(System.String sectionPath, System.Boolean globalConfigFile = true)
		{
			// open section
			EFS.Common.Config.Components.Section section =
				globalConfigFile ?
				EFS.Common.Config.Components.Section.Open("C:\\EFS.config", sectionPath): 
				EFS.Common.Config.Components.Section.Open(sectionPath);

			// check
			if (null == section)
			{
				throw new System.Exception(System.String.Format("globalConfigFile={0}; sectionPath={1}", globalConfigFile, sectionPath));
			}
			
			// load plain
			foreach (EFS.Common.Config.Components.Elements.Element element in section.Plain)
			{
				// add
				elements.Add(element.Name, element);
			}
		}

		/// Tries to create the reader
		public static Reader TryCreateReader(System.String sectionPath, System.Boolean globalConfigFile = true)
		{
			try
			{
				return new Reader(sectionPath, globalConfigFile);
			}
			catch {}

			// failed
			return null;
		}

		/// <summary>
		/// Get attribute
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public System.String GetAttributeString(System.String key)
		{
		    // get entry
			EFS.Common.Config.Components.Elements.Element element = elements[key];

			// done
			return (element == null) ? null : element.Value;
		}

		/// <summary>
		/// Get Boolean
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public System.Boolean GetAttributeBoolean(System.String key, System.Boolean defaultValue = false)
		{
		    // get entry
			EFS.Common.Config.Components.Elements.Element element = elements[key];

			// done
			return (element == null) ? defaultValue : (element.Value.ToLower() == "true") ? true : false;
		}

		/// <summary>
		/// Get Int
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public System.Int32 GetAttributeInt(System.String key, System.Int32 defaultValue = 0)
		{
			// get entry
			EFS.Common.Config.Components.Elements.Element element = elements[key];

			try
			{
				System.Int32 returnValue;
				if (null != element && System.Int32.TryParse(element.Value.ToString(), out returnValue))
				{
					return returnValue;
				}
			}
			catch (System.Exception) { }

			// return
			return defaultValue;
		}		
	}
}
